<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>2-4-待办任务列表</title>
</head>

<body>


  <!--载入vue.js-->
  <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>

  <div id="Application">
    <!--输入框元素，用来新建待办任务-->
    <form @submit.prevent="addTask">
      <!--.prevent修改提交属性，使其提交不刷新页面-->
      <span>新建任务</span>
      <input v-model="taskText" placeholder="请输入任务..." />
      <button>添加</button>
    </form>

    <!--有序列表，使用v-for来构建-->
    <ol>
      <li v-for="item in todos" :key="keys">
        {{item}}
        <button @click="remove(keys)">删除任务</button>
        <hr />
      </li>
    </ol>
  </div>

  <script>
    const App = {
      data() {
        return {
          //待办任务列表数据
          todos: [],
          //当前输入的待办任务
          taskText: "",
        };
      },
      methods: {
        //添加一条待办任务
        addTask() {
          //判断输入框是否为空
          if (this.taskText.length == 0) {
            alert("请输入任务");
            return;
          }
          this.todos.push(this.taskText); //给数组添加新元素
          this.taskText = "";
        },
        //删除一条待办任务
        remove(keys) {
          this.todos.splice(keys, 1);
        },
      },
    };

    Vue.createApp(App).mount("#Application");
  </script>
</body>

</html>